package com.lvw.weather.gateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

/**
 * 自定义过滤器, 实现四个方法即可
 */
public class AccessFilter extends ZuulFilter {

    private static final Logger log = LoggerFactory.getLogger(AccessFilter.class);

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        RequestContext requestContext = RequestContext.getCurrentContext();

        HttpServletRequest request = requestContext.getRequest();
        String accessToken = request.getHeader("accessToken");

        log.info("send {} request to {}", request.getMethod(), request.getRequestURI());

/*

        if (accessToken == null) {
            log.info("Error: access token empty.");
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(401);
            return null;
        }
*/

        log.info("Access token is ok.");

        return null;
    }

    public void testException() {
        throw new RuntimeException("==============>I'm a test exception.");
    }
}
